package com.lzl.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.lzl.constant.TokenConstant;
import com.lzl.dto.TokenResult;
import com.lzl.responese.ResponseResult;
import com.lzl.util.JWTUtils;
import com.lzl.util.RedisPrefixUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * //TODO
 *
 * @author zhaolinlin
 * @description //TODO
 * @createTime 2022/8/7 19:55
 */

public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response ,Object handler) throws IOException {
       boolean result = true;
       String resultString = "";

       String token = request.getHeader("Authorization");
       //解析token
        TokenResult tokenResult = JWTUtils.checkToken(token);
        if(tokenResult == null){
            resultString = "access token invalid";
            result = false;
        }else{
            //拼接
            String phone = tokenResult.getPhone();
            String identity = tokenResult.getIdentity();

            String tokenKey = RedisPrefixUtils.generatorTokenKey(phone,identity, TokenConstant.ACCESS_TOKEN);
            //从redis中获取token
            String redisToken = stringRedisTemplate.opsForValue().get(tokenKey);
            if(StringUtils.isBlank(redisToken) || !token.trim().equals(redisToken) ){
                resultString = "access token invalid" ;
                result = false;
            }
        }

        if (!result){
            PrintWriter out = response.getWriter();
            out.print(JSONObject.fromObject(ResponseResult.fail(resultString)).toString());
        }



        return result;
    }
}
